package com.haier.dreambox.demo.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.widget.AdapterView;
import android.widget.ListView;
import com.haier.dreambox.demo.Constants;
import com.haier.dreambox.demo.MyApplication;
import com.haier.dreambox.demo.R;
import com.haier.dreambox.demo.SherlockActivity;
import com.haier.dreambox.demo.bean.Event.HaierCommandExeEvent;
import com.haier.dreambox.demo.bean.Event.HaieruDeviceListChangeEvent;
import com.haier.dreambox.demo.bean.Event.HaieruDeviceStatusEvent;
import com.haier.dreambox.demo.bean.uplus.Device;
import com.haier.dreambox.demo.fragment.AddDevFragment_;
import com.haier.dreambox.demo.fragment.IControlPageInterface;
import com.haier.dreambox.demo.ui.adapter.MenuAdapter;
import com.haier.dreambox.demo.ui.adapter.MenuItem;
import com.haier.dreambox.demo.ui.adapter.PagerAdapter;
import com.haier.dreambox.demo.utils.DialogUtil;
import com.haier.dreambox.demo.utils.MyPrefs_;
import com.haier.dreambox.demo.utils.ToastUtils;
import com.haier.dreambox.lib.sherlock.app.ActionBar;
import com.haier.dreambox.lib.usdklib.UsdkConst;
import com.haier.dreambox.lib.usdklib.wrapper.uPlusManager;
import com.haier.dreambox.lib.view.indicator.CirclePageIndicator;
import com.haier.uhome.usdk.api.*;
import de.greenrobot.event.EventBus;
import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;
import org.androidannotations.annotations.*;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.api.BackgroundExecutor;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


/**
 * 主界面Activity
 */
@EActivity
public class HomeActivity extends SherlockActivity implements ActionBar.OnNavigationListener, MenuAdapter.MenuListener {


    private static final String TAG = "HomeActivity";


    private static final String STATE_ACTIVE_POSITION =
            "net.simonvt.menudrawer.samples.LeftDrawerSample.activePosition";
    private static final String TAG_SDK_APP_LOG = TAG;
    private static final int REQUEST_CODE_UNBIND = 100;
    private static final int OPTION_MENU_ID_UNBIND = 12;
    private static final int OPTION_MENU_ID_ABOUT = 13;
    private static final int OPTION_MENU_ID_SETTING = 14;

    protected MenuDrawer mMenuDrawer;
    protected MenuAdapter mAdapter;
    protected ListView mList;

    @Bean
    ToastUtils toastUtils;

    @Pref
    MyPrefs_ pref;

    @App
    MyApplication application;

    private int mActivePosition = 0;

    private ProgressDialog progressDialog;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_ACTIVE_POSITION, mActivePosition);
    }

    @Override
    public void onActiveViewChanged(View v) {
        mMenuDrawer.setActiveView(v, mActivePosition);
    }

    private PagerAdapter mPagerAdapter;
    private ViewPager mViewPager;
    private int mPagerOffsetPixels;
    private int mPagerPosition;
    private CirclePageIndicator mIndicator;

    @Override
    protected void onCreate(Bundle inState) {
        setTheme(R.style.Theme_Sherlock);
        super.onCreate(inState);

        if (inState != null) {
            mActivePosition = inState.getInt(STATE_ACTIVE_POSITION);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        addLeftMenu();

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        changePagerContent(0);

        progressDialog = DialogUtil.buildProgressDialog(this, "等待空调响应...", new Runnable() {
            @Override
            public void run() {
                BackgroundExecutor.cancelAll("login", true);
            }
        });

        uiHandler = new HomeHandler(this);
        startHaierSDk();
    }

    private void changePagerContent(int menuItemIndex) {
        if (mPagerAdapter != null) {
            mPagerAdapter.clearCache();
        }
        mPagerAdapter = new PagerAdapter(this);

        List<Device> devices = application.getCachedUserDevices();
        Device device = null;
        if (menuItemIndex < devices.size()) {
            device = devices.get(menuItemIndex);
        }

        if (device != null) {
            Class clz = Constants.getFragmentByClz(device.type.typeIdentifier);
            if (clz != null) {
                Bundle bundle = new Bundle();
                bundle.putString("mac", device.mac);
                //添加tab Fragment
                mPagerAdapter.addTab(clz, bundle);
            }
        }

        mPagerAdapter.addTab(AddDevFragment_.class, null);
        mViewPager.setAdapter(mPagerAdapter);

        //设置indicator
        mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        mIndicator.setViewPager(mViewPager);
        mIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mPagerPosition = position;
                mPagerOffsetPixels = positionOffsetPixels;
            }

        });

    }

    //===============================左侧菜单=====================================

    private void addLeftMenu() {
        mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.BEHIND, getDrawerPosition(), getDragMode());

        mList = new ListView(this);
        mAdapter = new MenuAdapter(this, getItems());
        mAdapter.setListener(this);
        mAdapter.setActivePosition(mActivePosition);

        mList.setAdapter(mAdapter);
        mList.setOnItemClickListener(mItemClickListener);
        mMenuDrawer.setMenuView(mList);

        //设置左侧菜单
        mMenuDrawer.setContentView(R.layout.activity_viewpagersample);
        mMenuDrawer.setDrawerIndicatorEnabled(true);
        mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
        mMenuDrawer.setOnInterceptMoveEventListener(new MenuDrawer.OnInterceptMoveEventListener() {
            @Override
            public boolean isViewDraggable(View v, int dx, int x, int y) {
                if (v == mViewPager) {
                    return !(mPagerPosition == 0 && mPagerOffsetPixels == 0) || dx < 0;
                }
                return false;
            }
        });

    }

    private List<Object> getItems() {
        List<Object> items = new ArrayList<Object>();
        List<Device> devices = application.getCachedUserDevices();
        if (devices != null) {
            for (Device device : devices) {
                items.add(new MenuItem(device.name, R.drawable.ic_action_select_all_dark));
            }
        }
        return items;
    }

    protected Position getDrawerPosition() {
        return Position.LEFT;
    }

    protected int getDragMode() {
        return MenuDrawer.MENU_DRAG_CONTENT;
    }

    private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mActivePosition = position;
            mMenuDrawer.setActiveView(view, position);
            mAdapter.setActivePosition(position);
            onMenuItemClicked(position, (MenuItem) mAdapter.getItem(position));
        }
    };

    protected void onMenuItemClicked(int position, MenuItem item) {
        changePagerContent(position);
        mMenuDrawer.closeMenu();
    }
    //===============================左侧菜单END=====================================


    @Override
    public void onBackPressed() {
        final int drawerState = mMenuDrawer.getDrawerState();
        if (drawerState == MenuDrawer.STATE_OPEN
                || drawerState == MenuDrawer.STATE_OPENING) {
            mMenuDrawer.closeMenu();
            return;
        }

        super.onBackPressed();
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        return false;
    }


    //===============================option菜单=====================================
    @Override
    public boolean onCreateOptionsMenu(com.haier.dreambox.lib.sherlock.view.Menu menu) {
        //创建Actionbar actions
        com.haier.dreambox.lib.sherlock.view.SubMenu subMenu = menu.addSubMenu("Action Item");
        subMenu.add(12, OPTION_MENU_ID_UNBIND, 0, "解绑");
        subMenu.add(12, OPTION_MENU_ID_ABOUT, 1, "关于");
        subMenu.add(12, OPTION_MENU_ID_SETTING, 2, "设置");

        com.haier.dreambox.lib.sherlock.view.MenuItem subMenu1Item = subMenu.getItem();
        subMenu1Item.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
        subMenu1Item.setShowAsAction(com.haier.dreambox.lib.sherlock.view.MenuItem.SHOW_AS_ACTION_ALWAYS
                | com.haier.dreambox.lib.sherlock.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mMenuDrawer.toggleMenu();
                return true;
            case OPTION_MENU_ID_UNBIND:
                UnBindActivity_.intent(this).startForResult(REQUEST_CODE_UNBIND);
                break;

        }

        return super.onOptionsItemSelected(item);
    }
    //===============================option菜单END=====================================


    @OnActivityResult(REQUEST_CODE_UNBIND)
    void onResult(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mAdapter.setItems(getItems());
            changePagerContent(0);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        sdkManager.clearUSDKDevices();

    }

    public void onEvent(HaieruDeviceListChangeEvent event) {

        StringBuilder sb = new StringBuilder();
        sb.append("新增了" + event.newDeviceMacList.size() + "台设备");

        uSDKErrorConst result = sdkManager.subscribeDevices(event.newDeviceMacList);

        if (uSDKErrorConst.RET_USDK_OK.equals(result.getValue())) {

            Fragment fragment = mPagerAdapter.getFragmentByPosition(mViewPager.getCurrentItem());

            if (fragment instanceof IControlPageInterface) {
                IControlPageInterface controlPageInterface = (IControlPageInterface) fragment;
                for (String mac : event.newDeviceMacList) {
                    if (mac.equals(controlPageInterface.getBindMac())) {
                        controlPageInterface.refreshControlView(sdkManager.getDeviceAttributeValues(mac));
                    }
                }
            }

        }
        toastUtils.showShort(this, "订阅设备: " + sb.toString() + "--->" + result.getValue());

    }

    public void onEvent(HaierCommandExeEvent event) {
        if (event.isCommandNormalComplete()) {
            if (event.isAfterCommandExe) {
                progressDialog.dismiss();
            } else {
                progressDialog.show();
            }
            toastUtils.showShort(this, event.errorConst.getValue());
        } else {
            toastUtils.showShort(this, "命令执行失败");
        }


    }

    public void onEvent(HaieruDeviceStatusEvent event) {

        Fragment fragment = mPagerAdapter.getFragmentByPosition(mViewPager.getCurrentItem());

        if (fragment instanceof IControlPageInterface) {
            IControlPageInterface controlPageInterface = (IControlPageInterface) fragment;
            if (controlPageInterface.getBindMac().equals(event.getMac())) {
                controlPageInterface.refreshControlView(event.getAttributes());
            }
        }

    }

    // ========================================================================================

    @Background
    void startHaierSDk() {
        uSDKErrorConst sdkStartResult = sdkManager.startSdk(this, uiHandler);
        toastUtils.showShort(this, "SDK启动结果" + sdkStartResult.getValue());

        String remoteLoginUrl = pref.userGateway().get();
        if (!TextUtils.isEmpty(remoteLoginUrl)) {
            int lastColonIndex = remoteLoginUrl.lastIndexOf(":");

            String urlPath = remoteLoginUrl.substring(0, lastColonIndex);
            int port = Integer.parseInt(remoteLoginUrl.substring(lastColonIndex + 1, remoteLoginUrl.length()));
            Log.i(TAG, "urlPath: " + urlPath + "port: " + port);
            uSDKErrorConst remoteLoginResult = sdkManager.uDeviceRemoteLogin(urlPath,
                    port,
                    pref.accessToken().get(),
                    generateRemoteLoginuSDKDevice());

            toastUtils.showShort(this, "SDK远程登录结果" + remoteLoginResult.getValue());
        }

        sdkManager.subscribeDeviceListChange(
                uSDKDeviceTypeConst.UNKNOWN,
                uSDKDeviceTypeConst.SPLIT_AIRCONDITION,
                uSDKDeviceTypeConst.COMMERCIAL_AIRCONDITION);

    }


    public ArrayList<uSDKDevice> generateRemoteLoginuSDKDevice() {
        ArrayList<uSDKDevice> mSdkDevices = new ArrayList<uSDKDevice>();
        if (application.getCachedUserDevices() != null) {
            for (Device device : application.getCachedUserDevices()) {
                String mac = device.mac;
                String typeIdentifier = (device.type != null) ? device.type.typeIdentifier
                        : "";
                String smartLinkVersion = ((device.version != null) && (device.version.smartlink != null)) ? device.version.smartlink.smartLinkSoftwareVersion
                        : "";
                String smartLinkPlatform = ((device.version != null) && (device.version.smartlink != null)) ? device.version.smartlink.smartLinkPlatform
                        : "";
                uSDKDevice mSdkDevice = uSDKDevice.newRemoteDeviceInstance(mac,
                        typeIdentifier, uSDKDeviceStatusConst.STATUS_ONLINE,
                        smartLinkVersion, smartLinkPlatform);
                mSdkDevices.add(mSdkDevice);
            }
        }
        return mSdkDevices;
    }


    public Handler uiHandler;


    private static class HomeHandler extends Handler {

        private WeakReference<HomeActivity> mActs = null;
        private uPlusManager sdkManger;

        public HomeHandler(HomeActivity act) {
            mActs = new WeakReference<HomeActivity>(act);
            sdkManger = act.sdkManager;
        }

        @Override
        public void handleMessage(Message msg) {
            if (mActs == null) return;

            final HomeActivity act = mActs.get();

            if (act == null) {
                this.removeCallbacksAndMessages(null);
                return;
            }

            switch (msg.what) {
                case uSDKNotificationCenter.DEVICE_LIST_CHANGED_NOTIFY:// 设备列表变化
                    // 返回类型 ArrayList<uSDKDevice>
                    ArrayList<uSDKDevice> devices = (ArrayList<uSDKDevice>) msg.obj;
                    if (devices != null) {
                        List<String> macList = sdkManger.addUSDKDevices(devices, mActs.get().application.getCachedUserDeviceMacs());
                        if (!macList.isEmpty()) {
                            EventBus.getDefault().post(new HaieruDeviceListChangeEvent(macList));
                        }
                    }
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备在列表变化:" + msg);
                    break;

                case uSDKNotificationCenter.DEVICE_ONLINE_CHANGED_NOTIFY:// 设备在线状态变化
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备在线状态变化:" + msg);

                    break;

                case uSDKNotificationCenter.DEVICE_BIND_MESSAGE_NOTIFY://  设备绑定消息上报
                    // 返回类型:HashMap<String,String>
                    // key:session,value:mac
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备绑定消息上报:" + msg);
                    break;
                case UsdkConst.MSG_USDK_COMMAND_EXE_BEGIN:// 执行指令前
                    EventBus.getDefault().post(new HaierCommandExeEvent(false, (uSDKErrorConst) msg.obj));
                    break;

                case UsdkConst.MSG_USDK_COMMAND_EXE_END:// 执行指令后
                    EventBus.getDefault().post(new HaierCommandExeEvent(true, (uSDKErrorConst) msg.obj));

                    break;

                case uSDKNotificationCenter.DEVICE_STATUS_CHANGED_NOTIFY:// 设备状态变化
                    // 返回类型 HashMap<String,HashMap<String,uSDKDeviceAttribute>>属性集
                    // key:设备mac,value:属性集合
                    // 属性集合的key:属性的name,value:属性实体
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备状态变化:" + msg);
                    EventBus.getDefault().post(new HaieruDeviceStatusEvent(msg));
                    break;
                case uSDKNotificationCenter.DEVICE_UNBIND_MESSAGE_NOTIFY:// 设备解绑消息上报
                    // 返回类型  HashMap<String,String>
                    // key:session, value:mac
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备解绑消息上报:" + msg);
                    break;
                case uSDKNotificationCenter.SESSION_EXCEPTION_NOTIFY:// 设备SESSION异常上报
                    // String 失效的那个session字符串
//                    remoteLogin();
//                    onUsdkDeviceRefreshViews(msg);
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备SESSION异常上报:" + msg);
                    break;
                case uSDKNotificationCenter.USDKSERVER_EXCEPTION_NOTIFY:// 设备Sever异常上报
                    // uSDKErrorConst 错误码
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备Sever异常上报:" + msg);
                    break;
//
                case uSDKNotificationCenter.DEVICE_ALARM_NOTIFY:// 设备报警上报 返回类型
                    // HashMap<String,ArrayList<uSDKDeviceAlarm>>报警列表
                    // key:设备mac,value:报警列表
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备报警上报:" + msg);
                    break;
//                case uSDKNotificationCenter.DEVICE_BIG_DATA_NOTIFY:// 设备大数据上报
//                    // 返回类型 uSDKTransparentMessage
//                    LogUtil.d("info", "--------------------设备大数据上报:" + msg);
//                    break;
//                case uSDKNotificationCenter.DEVICE_INFRARED_INFO_NOTIFY:// 设备红外消息上报
//                    // 返回类型 uSDKTransparentMessage
//                    LogUtil.d("info", "--------------------设备红外消息上报:" + msg);
//                    break;
                case uSDKNotificationCenter.BUSINESS_MESSAGE_NOFIFY://  设备业务消息上报
//                    // 返回类型 uSDKBusinessMessage
//                    try {
//                        UsdkPushMessageUtil.handleBusinessMessage(BaseActivity.this,
//                                (uSDKBusinessMessage) msg.obj, new PushMessageActionListener() {
//
//                                    @Override
//                                    public void onQueryButtonClick(String codeString) {
//                                        if ("000200012".equals(codeString)) {
//                                            new OperateDevice(BaseActivity.this).execute("leave");
//                                        } else if ("000200013".equals(codeString)) {
//                                            new OperateDevice(BaseActivity.this).execute("back");
//                                        }
//                                    }
//
//                                    @Override
//                                    public void onCancelButtonClick(String codeString) {
//                                    }
//                                }, UsdkPushMessageUtil.FROM_ACTIVITY);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    Log.d(TAG_SDK_APP_LOG, "--------------------设备业务消息上报:" + msg);
                    break;

                case uSDKNotificationCenter.USDK_ERROR_NOTIFY:// SDK内部错误上报
//                    handleUsdkError(msg);
                    break;
                default:

            }

        }


    }
}
